/**
 * 标准关联模块前端功能实现
 */

// API基本路径 - 使用与其他模块一致的方式
let relation_API_BASE = '/api/feibiao/relation';
let currentRelationPage = 0;
let relationPageSize = 10;
let currentRelationSearchKeyword = '';

// 将在DOMContentLoaded中初始化
document.addEventListener('DOMContentLoaded', function() {
    try {
        // 确保全局API_BASE已定义
        if (typeof API_BASE !== 'undefined') {
            relation_API_BASE = `${API_BASE}/feibiao/relation`;
        } else {
            console.warn('全局API_BASE未定义，使用默认API路径');
            relation_API_BASE = '/api/feibiao/relation';
        }
        
        // 如果当前页面是关联信息页面，自动加载数据
        const currentTarget = document.querySelector('.submenu-item.active')?.getAttribute('data-target');
        if (currentTarget === 'am_archives_relation') {
            loadStandardRelationList();
        }
    } catch (err) {
        console.error("标准关联模块初始化失败:", err);
    }
});

/**
 * 加载标准关联列表
 */
function loadStandardRelationList(page = 0, size = 10) {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 保存当前页码
    currentRelationPage = page;
    relationPageSize = size;
    
    
    // 发起请求获取数据，添加排序参数
    fetch(`${relation_API_BASE}?page=${page}&size=${size}&sort=relationId,asc`)
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    console.error('API请求失败:', response.status, response.statusText, text);
                    try {
                        const error = JSON.parse(text);
                        throw new Error(`服务器错误 (${response.status}): ${error.message || error.error || response.statusText}`);
                    } catch (e) {
                        if (e instanceof SyntaxError) {
                            throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                        }
                        throw e;
                    }
                });
            }
            return response.json();
        })
        .then(data => {
            renderStandardRelationTable(data);
        })
        .catch(error => {
            console.error('获取标准关联数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>错误信息: ${error.message}</p>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadStandardRelationList()">重试</button>
                    </div>
                </div>
            `;
            if (typeof showMessage === 'function') {
                showMessage('获取标准关联数据失败: ' + error.message, 'error');
            } else {
                console.error('showMessage函数未定义，无法显示错误消息');
            }
        });
}

/**
 * 渲染标准关联表格
 * @param {Object} data - 分页数据
 */
function renderStandardRelationTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">标准关联管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showStandardRelationForm()"></i> 新增</button>
            </div>
        </div>
        
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="relationSearchInput" placeholder="输入关键词搜索..." value="${currentRelationSearchKeyword}">
                <button class="search-btn" onclick="searchStandardRelation()">搜索</button>
                ${currentRelationSearchKeyword ? '<button class="btn btn-default" onclick="clearRelationSearch()">返回列表</button>' : ''}
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>电机ID</th>
                        <th>标准类型</th>
                        <th>标准值</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.relationId || ''}</td>
                    <td>${item.motorId || ''}</td>
                    <td>${item.standardType || ''}</td>
                    <td>${item.standardValue || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewStandardRelation(${item.relationId})">查看</a>
                        <a href="javascript:void(0)" onclick="editStandardRelation(${item.relationId})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteStandardRelation(${item.relationId})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="5" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    // 添加分页控件，使用与operation_test.js相同的样式
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentRelationPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentRelationPage <= 0 ? 'void(0)' : 'loadStandardRelationList(' + (currentRelationPage - 1) + ', ' + relationPageSize + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentRelationPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadStandardRelationList(${i}, ${relationPageSize})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentRelationPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentRelationPage >= data.totalPages - 1 ? 'void(0)' : 'loadStandardRelationList(' + (currentRelationPage + 1) + ', ' + relationPageSize + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 清除搜索
 */
function clearRelationSearch() {
    document.getElementById('relationSearchInput').value = '';
    currentRelationSearchKeyword = '';
    currentRelationPage = 0;
    loadStandardRelationList(0, relationPageSize);
}

/**
 * 搜索标准关联
 */
function searchStandardRelation() {
    const keyword = document.getElementById('relationSearchInput').value.trim();
    currentRelationSearchKeyword = keyword;
    currentRelationPage = 0;
    
    if (!keyword) {
        loadStandardRelationList(0, relationPageSize);
        return;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 尝试不同的搜索端点，首先尝试按照标准值搜索
    fetch(`${relation_API_BASE}/by-standard?standardCode=${encodeURIComponent(keyword)}&sort=relationId,asc`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            if (Array.isArray(data) && data.length > 0) {
                // 将列表结果包装为分页格式
                const pageData = {
                    content: data,
                    totalPages: 1,
                    number: 0,
                    size: data.length,
                    first: true,
                    last: true,
                    totalElements: data.length
                };
                renderStandardRelationTable(pageData);
                
                // 显示搜索信息
                const searchInfo = document.createElement('div');
                searchInfo.className = 'search-result-info';
                searchInfo.innerHTML = `搜索"${keyword}": 找到 ${data.length} 条记录`;
                document.querySelector('.content-toolbar').after(searchInfo);
            } else {
                // 没有找到，尝试按照电机ID搜索
                return fetch(`${relation_API_BASE}/by-motor?motorId=${encodeURIComponent(keyword)}&sort=relationId,asc`);
            }
        })
        .then(response => {
            if (!response || !response.ok) {
                return null;
            }
            return response.json();
        })
        .then(data => {
            if (data) {
                // 将列表结果包装为分页格式
                const pageData = {
                    content: data,
                    totalPages: 1,
                    number: 0,
                    size: data.length,
                    first: true,
                    last: true,
                    totalElements: data.length
                };
                renderStandardRelationTable(pageData);
                
                // 显示搜索信息
                const searchInfo = document.createElement('div');
                searchInfo.className = 'search-result-info';
                searchInfo.innerHTML = `搜索"${keyword}": 找到 ${data.length} 条记录`;
                document.querySelector('.content-toolbar').after(searchInfo);
            } else {
                if (typeof showMessage === 'function') {
                    showMessage('未找到匹配的标准关联数据', 'info');
                }
                renderStandardRelationTable({
                    content: [],
                    totalPages: 0,
                    number: 0,
                    size: 0,
                    first: true,
                    last: true,
                    totalElements: 0
                });
            }
        })
        .catch(error => {
            console.error('搜索标准关联数据失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('搜索标准关联数据失败: ' + error.message, 'error');
            }
            
            // 搜索失败时显示空结果
            renderStandardRelationTable({
                content: [],
                totalPages: 0,
                number: 0,
                size: relationPageSize,
                first: true,
                last: true,
                totalElements: 0
            });
        });
}

/**
 * 显示标准关联表单(新增/编辑)
 * @param {Object} data - 已有数据(编辑时传入)
 */
function showStandardRelationForm(relation = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = relation !== null;
    
    // 构建表单HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}标准关联</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadStandardRelationList(${currentRelationPage}, ${relationPageSize})">返回列表</button>
            </div>
        </div>
        
        <div class="form-container">
            <form id="standardRelationForm" onsubmit="return submitStandardRelationForm(event)">
                ${isEdit ? `<input type="hidden" id="relationId" value="${relation.relationId}">` : ''}
                
                <div class="form-group">
                    <label for="motorId">电机ID: <span class="required">*</span></label>
                    <input type="text" id="motorId" name="motorId" class="form-control" required
                           value="${isEdit && relation.motorId ? relation.motorId : ''}">
                </div>
                
                <div class="form-group">
                    <label for="standardType">标准类型: <span class="required">*</span></label>
                    <select id="standardType" name="standardType" class="form-control" required>
                        <option value="">-- 请选择 --</option>
                        <option value="SAFETY" ${isEdit && relation.standardType === 'SAFETY' ? 'selected' : ''}>安全标准</option>
                        <option value="PERFORMANCE" ${isEdit && relation.standardType === 'PERFORMANCE' ? 'selected' : ''}>性能标准</option>
                        <option value="ENVIRONMENTAL" ${isEdit && relation.standardType === 'ENVIRONMENTAL' ? 'selected' : ''}>环境标准</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="standardValue">标准值: <span class="required">*</span></label>
                    <input type="text" id="standardValue" name="standardValue" class="form-control" required
                           value="${isEdit && relation.standardValue ? relation.standardValue : ''}">
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">${isEdit ? '更新' : '保存'}</button>
                    <button type="button" class="btn btn-default" onclick="loadStandardRelationList(${currentRelationPage}, ${relationPageSize})">取消</button>
                </div>
            </form>
        </div>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 提交标准关联表单
 * @param {Event} event - 表单提交事件
 */
function submitStandardRelationForm(event) {
    event.preventDefault();
    
    // 获取表单数据
    const motorId = document.getElementById('motorId').value.trim();
    const standardType = document.getElementById('standardType').value;
    const standardValue = document.getElementById('standardValue').value.trim();
    
    // 数据验证
    if (!motorId) {
        if (typeof showMessage === 'function') {
            showMessage('请输入电机ID', 'error');
        }
        return false;
    }
    
    if (!standardType) {
        if (typeof showMessage === 'function') {
            showMessage('请选择标准类型', 'error');
        }
        return false;
    }
    
    if (!standardValue) {
        if (typeof showMessage === 'function') {
            showMessage('请输入标准值', 'error');
        }
        return false;
    }
    
    const formData = {
        motorId: motorId,
        standardType: standardType,
        standardValue: standardValue
    };
    
    const relationId = document.getElementById('relationId');
    const isEdit = relationId !== null && relationId !== undefined;
    const url = isEdit ? `${relation_API_BASE}/${relationId.value}` : relation_API_BASE;
    const method = isEdit ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
            });
        }
        return response.json();
    })
    .then(data => {
        if (typeof showMessage === 'function') {
            showMessage(`${isEdit ? '更新' : '新增'}标准关联成功`, 'success');
        }
        loadStandardRelationList(currentRelationPage, relationPageSize);
    })
    .catch(error => {
        console.error(`${isEdit ? '更新' : '新增'}标准关联失败:`, error);
        if (typeof showMessage === 'function') {
            showMessage(`${isEdit ? '更新' : '新增'}标准关联失败: ` + error.message, 'error');
        }
    });
    
    return false;
}

/**
 * 查看标准关联详情
 * @param {number} id - 记录ID
 */
function viewStandardRelation(id) {
    fetch(`${relation_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(relation => {
            showStandardRelationDetail(relation);
        })
        .catch(error => {
            console.error('获取标准关联详情失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取标准关联详情失败: ' + error.message, 'error');
            }
        });
}

/**
 * 显示标准关联详情
 * @param {Object} relation - 详情数据
 */
function showStandardRelationDetail(relation) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">标准关联详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadStandardRelationList(${currentRelationPage}, ${relationPageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${relation.relationId || '--'}</div></div>
            <div class="detail-group"><label>电机ID:</label><div>${relation.motorId || '--'}</div></div>
            <div class="detail-group"><label>标准类型:</label><div>${relation.standardType || '--'}</div></div>
            <div class="detail-group"><label>标准值:</label><div>${relation.standardValue || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editStandardRelation(${relation.relationId})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteStandardRelation(${relation.relationId})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadStandardRelationList(${currentRelationPage}, ${relationPageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

/**
 * 编辑标准关联
 * @param {number} id - 记录ID
 */
function editStandardRelation(id) {
    fetch(`${relation_API_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            return response.json();
        })
        .then(relation => {
            showStandardRelationForm(relation);
        })
        .catch(error => {
            console.error('获取标准关联详情失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取标准关联详情失败: ' + error.message, 'error');
            }
        });
}

/**
 * 删除标准关联
 * @param {number} id - 记录ID
 */
function deleteStandardRelation(id) {
    if (confirm('确定要删除这条标准关联吗？此操作不可恢复!')) {
        fetch(`${relation_API_BASE}/${id}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
            }
            if (typeof showMessage === 'function') {
                showMessage('删除标准关联成功', 'success');
            }
            loadStandardRelationList(currentRelationPage, relationPageSize);
        })
        .catch(error => {
            console.error('删除标准关联失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('删除标准关联失败: ' + error.message, 'error');
            }
        });
    }
}

/**
 * 格式化日期时间
 * @param {string|object} datetime - 日期时间对象或字符串
 * @returns {string} 格式化后的日期时间
 */
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 格式化日期为input date控件的值
 * @param {string} dateString - 日期字符串
 * @returns {string} 格式化后的日期 (YYYY-MM-DD)
 */
function formatDateForInput(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toISOString().split('T')[0];
}
if (typeof window !== 'undefined') {
// 将函数暴露给全局
    window.loadStandardRelationList = loadStandardRelationList;
    window.renderStandardRelationTable = renderStandardRelationTable;
    window.showStandardRelationForm = showStandardRelationForm;
    window.submitStandardRelationForm = submitStandardRelationForm;
    window.viewStandardRelation = viewStandardRelation;
    window.showStandardRelationDetail = showStandardRelationDetail;
    window.editStandardRelation = editStandardRelation;
    window.deleteStandardRelation = deleteStandardRelation;
    window.searchStandardRelation = searchStandardRelation;
    window.clearRelationSearch = clearRelationSearch;
}
